package com.yun.util.listen;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.read.metadata.ReadSheet;
import org.springframework.context.ApplicationContext;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;


/**
 * 导入处理器   。。。添加线程池？暂时不用
 */
public class ImportProcessor {


    /**
     * excel文件导入
     * @param multipartFile     文件
     * @param classname         类名
     * @throws Exception        异常
     */
    public void imports(MultipartFile multipartFile, String classname) throws Exception {
        String filename = multipartFile.getOriginalFilename();
        if (filename==null){
            throw new Exception("文件名不存在");
        }
        if (!filename.endsWith(".xls")&&!filename.endsWith(".xlsx")){
            throw new Exception("文件后缀格式错误");
        }
        ExcelReader excelReader = null;
        //类
        Class<?> clazz = null;
        //实体对象注解值
        Map<Class<?>, List<ExcelProperty>> listMap = ImportReportCenter.getEntity(classname);
        for (Map.Entry<Class<?>, List<ExcelProperty>> entry : listMap.entrySet()) {
            if (entry.getValue() != null) {
                clazz = entry.getKey();
            }
        }
        if (clazz == null){
            throw new Exception("导出失败，请确定类名是否正确");
        }

        //获取导出对象类注解
        ExcelInit annotation = clazz.getAnnotation(ExcelInit.class);

        //封装业务方法数据格式
        Method method = null;
        Object instance = new Object();
        try {
            method = getMethod(clazz,annotation);
            instance = annotation.implType().newInstance();
        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        if (method==null){
            throw new Exception("导出失败，没找到执行方法");
        }
        try {
            String[] filenameArray = filename.split("\\.");
            File file=File.createTempFile(filenameArray[0], "."+filenameArray[1]);
            multipartFile.transferTo(file);
            excelReader = EasyExcel.read(file, clazz, new ExcelListener(ImportReportCenter.getContext(),instance,method)).build();
            ReadSheet readSheet = EasyExcel.readSheet(0).headRowNumber(1).build();
            excelReader.read(readSheet);
        }catch (IOException e){
            e.getMessage();
        } finally {
            if (excelReader != null) {
                excelReader.finish();
            }
        }
    }

    /**
     * 业务类执行方法
     * @param annotation   自定义导出注解类的实例
     * @param key          实体类
     * @return  方法数组
     */
    private Method getMethod(Class<?> key, ExcelInit annotation) throws NoSuchMethodException {
        Class<?> type = annotation.implType();
        return type.getMethod(annotation.saveMethodName(), key, ApplicationContext.class);
    }
}
